import asyncio
import aiomysql
from asyncio.queues import Queue

class QueueManager:
    def __init__(self, queue):
        self.queue = queue

    def enqueue_data(self, data):
        self.queue.put_nowait(data)

class DatabaseWriter:
    def __init__(self, queue, pool):
        self.queue = queue
        self.pool = pool

    async def initialize_db(self):
        self.pool = await aiomysql.create_pool(
            host='rm-uf6h021c725h86guaro.mysql.rds.aliyuncs.com',
            port=3306,
            user='loncus',
            password='Loncus1234&',
            db='metabase_sub-c_test',
            minsize=5,
            maxsize=10
        )

    async def write_to_db(self, data):
        async with self.pool.acquire() as conn:
            async with conn.cursor() as cur:
                # Assuming your_table_name is the table you want to insert into
                await cur.execute("INSERT INTO t_strategy_data (strategy_id,message) VALUES (%s,%s)", data)
                await conn.commit()

    async def process_queue(self):
        while True:
            data = await self.queue.get()
            if data is None:
                # Signal to stop processing
                break
            await self.write_to_db(data)

    async def cleanup(self):
        self.pool.close()
        await self.pool.wait_closed()

async def main():
    queue = Queue()
    queue_manager = QueueManager(queue)

    database_writer = DatabaseWriter(queue, None)

    # Initialize the database connection
    await database_writer.initialize_db()

    # Start the database writer coroutine
    writer_task = asyncio.create_task(database_writer.process_queue())

    # Simulate enqueuing data
    for i in range(10):
        data = (f"Value {i}", f"Another Value {i}")
        queue_manager.enqueue_data(data)

    # Signal the end of enqueuing
    queue_manager.enqueue_data(None)

    # Wait for the writer to finish processing
    await writer_task

    # Cleanup the database connection
    await database_writer.cleanup()

if __name__ == "__main__":
    loop = asyncio.get_event_loop()
    loop.run_until_complete(main())
